#include <JXQIO/JProcess>
#include <JXQCore/JThread>
#include <JXQCore/JDebug>

using namespace std;
using namespace JXQ;

J_SLOT func(JAbstractIO *io)
{
	jDebug() << "~~~~~" << io << io->readAll() << "\n";
}

int main(int argc, char *argv[])
{
	J_UNUSED(argc);
	J_UNUSED(argv);

	jDebug() << "sss----------------------------------------------";

	JProcess jp; //默认是全缓冲
	jp.setBufferMode(JProcess::LineBuffer); //设置为行缓冲
	jp.readyRead.subscribe(func);

	auto res = jp.execute([](const JStringList&)
	{
		for(int i=0; i<4; i++)
		{
			jDebug() << "child process out";
			jError() << "child process error";
			JThread::msleep(500);
		}
		return 0;
	});
	jDebug() << res.ret << res.stdOut << "\n" << res.stdError << "\n";

	jDebug() << "pid =" << jp.start([](const JStringList&)
	{
		JThread::sleep(2);

		char buf[1024] = "";
		int res = scanf("%[^\n]", buf);

		jDebug() << buf << "\n%%%--------\n-------%%" << res;
		if( res < 0 )
			 jDebug() << strerror(errno);

		JThread::sleep(1);
		return 0;
	});

	for(int i=0; i<3; i++)
		jp.write("come on  ", 9);
	jp.write("\n");
//	jp.flush();
//	jDebug() << "******** detach:" << jp.detach();
	jDebug() << ":::::" << jp.waitFinished();

	res = jp.execute("ls", {"-l", "-h"});
	jDebug() << res.ret << res.stdOut << "\n" << res.stdError;

	return res.ret;
}
